﻿using System;
using System.Collections.Generic;
using System.Data.Sql;
using System.Linq;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;

/// <summary>
/// Summary description for ScheduleController
/// </summary>
[AllowedRole("DictionaryAdmin")]
public class ScheduleController : EntityListController<Schedule,NotarialServiceDataContext>
{
    private int _TypeId = 0;
    private DateTime _Date = DateTime.Now;

    public void Schedule(string scheduleId)
    {
        LayoutPath = "~/views/layouts/page.haml";
        TemplatePath = "~/views/schedule/list.haml";
        ViewData["nofooter"] = true;
        RegisterScript("schedule/schedule.js");
        RegisterStylesheet("schedule/schedule.css");

        int sid = 0;
        if (!Int32.TryParse(scheduleId, out sid)) throw new IntraVisionWebException(404);

        PrepareSchedule(CalendarViewType.Month, sid);
    }

    private void PrepareSchedule(CalendarViewType period)
    {
        int sid = 0;
        if (!Int32.TryParse(Request["scheduleid"], out sid)) throw new IntraVisionWebException(404);
        PrepareSchedule(period, sid);
    }

    private void PrepareSchedule(CalendarViewType period, int scheduleid)
    {
        if(Action.ToUpperInvariant() != "SCHEDULE") LayoutPath = "none";
        TemplatePath = "~/views/schedule/_" + Action + ".haml";

        using (var dc = new NotarialServiceDataContext())
        {
            var date = (!string.IsNullOrEmpty(Request["date"])) ? DateTime.Parse(Request["date"]) : DateTime.Today;
            ViewData["Date"] = date;

            //Тип расписания - интернет, живая очередь и т.п.
            ViewData["ScheduleId"] = scheduleid;
            ViewData["Schedule"] = dc.Schedules.SingleOrDefault(s => s.Id == scheduleid);
            ViewData["Schedules"] = dc.Schedules.OrderBy(s => s.Name).ToList();
            //Покажем периоды только за нужный год
            ViewData["Periods"] = dc.SchedulePeriods.Where(p => p.ScheduleId == scheduleid && (p.DateStart.Year <= date.Year && (!p.DateEnd.HasValue || p.DateEnd.Value.Year >= date.Year))).OrderBy(p => p.DateStart).ToList();
            
            DateTime firstday = date;
            DateTime periodEnd = date;
            
            switch (period)
            {
                case CalendarViewType.Day:
                    firstday = DateTime.Today;
                    periodEnd = DateTime.Today;
                    break;
                case CalendarViewType.Week:
                    firstday = date.AddDays(-1 * (date.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)date.DayOfWeek) + 1);
                    periodEnd = firstday.AddDays(7);
                    break;
                case CalendarViewType.Month:
                    firstday = new DateTime(date.Year, date.Month, 1);
                    int dow = firstday.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)firstday.DayOfWeek;
                    int rows = (int)Math.Ceiling(((double)dow - 1 + DateTime.DaysInMonth(date.Year, date.Month)) / 7);
                    ViewData["Rows"] = rows;
                    firstday = firstday.AddDays(-1 * dow + 1);
                    periodEnd = firstday.AddDays(rows * 7);
                    break;
            }

            ViewData["Firstday"] = firstday;

            RenderView();
        }
    }

    public void GetPeriods()
    {
        int scheduleid = 0;
        if (!Int32.TryParse(Request["scheduleid"], out scheduleid)) throw new IntraVisionWebException(404);
        var date = (!string.IsNullOrEmpty(Request["date"])) ? DateTime.Parse(Request["date"]) : DateTime.Today;
        ViewData["Date"] = date;

        LayoutPath = "";
        TemplatePath = "~/views/schedule/_periods.haml";

        using (var dc = new NotarialServiceDataContext())
        {
            //Покажем периоды только за нужный год
            ViewData["Periods"] = dc.SchedulePeriods.Where(p => p.ScheduleId == scheduleid && (p.DateStart.Year <= date.Year && (!p.DateEnd.HasValue || p.DateEnd.Value.Year >= date.Year))).OrderBy(p => p.DateStart).ToList();
        }
        RenderView();
    }

    public void GetExceptions()
    {
        int scheduleid = 0;
        if (!Int32.TryParse(Request["scheduleid"], out scheduleid)) throw new IntraVisionWebException(404);
        var date = (!string.IsNullOrEmpty(Request["date"])) ? DateTime.Parse(Request["date"]) : DateTime.Today;
        ViewData["Date"] = date;

        LayoutPath = "";
        TemplatePath = "~/views/schedule/_exceptions.haml";

        using (var dc = new NotarialServiceDataContext())
        {
            //Покажем исключения только за нужный год
            ViewData["Exceptions"] = dc.ScheduleDayExceptions.Where(e => e.ScheduleId == scheduleid && e.Date.Year == date.Year).OrderBy(e => e.Date).ToList();
        }
        RenderView();
    }

    public void Month()
    {
        PrepareSchedule(CalendarViewType.Month);
    }
    
    public void Week()
    {
        PrepareSchedule(CalendarViewType.Week);
    }
    
    public void Day()
    {
        PrepareSchedule(CalendarViewType.Day);
    }

    public void DayDetails(string scheduleid, string sdate)
    {
        LayoutPath = "none";
        TemplatePath = "~/views/schedule/daydetails.haml";
        
        DateTime date = DateTime.Parse(sdate);
        ViewData["date"] = date;

        using (var dc = new NotarialServiceDataContext())
        {
            int sid = 0;
            Int32.TryParse(scheduleid, out sid);
            var schedule = dc.Schedules.SingleOrDefault(s => s.Id == sid);
            if (schedule != null)
            {
                ViewData["schedule"] = schedule;
                ViewData["scheduleday"] = schedule.GetWorkingHours(date);
            }
            RenderView();
        }
    }

    public override void Create()
    {
        LayoutPath = "~/Views/Layouts/popup.haml";
        ViewData["popup"] = true;
        base.Create();
    }

    public override void Save()
    {
        LayoutPath = "~/Views/Layouts/popup.haml";
        ViewData["popup"] = true;
        base.Save();
    }

    public override void View(string entityid)
    {
        LayoutPath = "~/Views/Layouts/popup.haml";
        ViewData["whitebg"] = true;
        base.View(entityid);
    }
}
